import 'package:flutter/material.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:get/get.dart';
import 'package:openim_common/openim_common.dart';

import '../../../core/controller/im_controller.dart';

enum EditAttr {
  nickname,
  englishName,
  telephone,
  mobile,
  email,
  bio,
  area,
}

class EditMyInfoLogic extends GetxController {
  final imLogic = Get.find<IMController>();
  late TextEditingController inputCtrl;
  late EditAttr editAttr;
  late int maxLength;
  String? title;
  String? defaultValue;
  TextInputType? keyboardType;
  TextEditingController? areaCodeCtrl;
  String? areaCodeDefault;
  final areaCode = ''.obs;

  @override
  void onInit() {
    editAttr = Get.arguments['editAttr'];
    maxLength = Get.arguments['maxLength'] ?? 16;
    _initAttr();
    inputCtrl = TextEditingController(text: defaultValue);
    if (editAttr == EditAttr.mobile) {
      final ac = areaCodeDefault ?? '';
      final code = ac.isEmpty ? '+86' : (ac.startsWith('+') ? ac : '+$ac');
      areaCodeCtrl = TextEditingController(text: code);
      areaCode.value = code;
    }
    super.onInit();
  }

  void openCountryCodePicker() async {
    String? code = await IMViews.showCountryCodePicker();
    if (code != null) {
      areaCodeCtrl?.text = code;
      areaCode.value = code;
    }
  }

  _initAttr() {
   switch (editAttr) {
      case EditAttr.nickname:
        title = StrRes.name;
        defaultValue = imLogic.userInfo.value.nickname;
        keyboardType = TextInputType.text;
        break;
      case EditAttr.englishName:
        title = '英文名';
        defaultValue = imLogic.userInfo.value.englishName;
        keyboardType = TextInputType.text;
        break;
      case EditAttr.telephone:
        title = '电话';
        defaultValue = imLogic.userInfo.value.telephone;
        keyboardType = TextInputType.phone;
        break;
      case EditAttr.mobile:
        title = StrRes.mobile;
        defaultValue = imLogic.userInfo.value.phoneNumber;
        areaCodeDefault = imLogic.userInfo.value.areaCode;
        keyboardType = TextInputType.phone;
        break;
      case EditAttr.email:
        title = StrRes.email;
        defaultValue = imLogic.userInfo.value.email;
        keyboardType = TextInputType.emailAddress;
        break;
      case EditAttr.bio:
        title = '简介';
        defaultValue = imLogic.userInfo.value.ex;
        keyboardType = TextInputType.multiline;
        break;
      case EditAttr.area:
        title = '地区';
        defaultValue = imLogic.userInfo.value.areaCode;
        keyboardType = TextInputType.text;
        break;
    }
  }

   void save() async {
    final value = inputCtrl.text.trim();
    if (editAttr == EditAttr.nickname) {
      await LoadingView.singleton.wrap(
        asyncFunction: () => Apis.updateUserInfo(
          userID: OpenIM.iMManager.userID,
          nickname: value,
        ),
      );
      imLogic.userInfo.update((val) {
        val?.nickname = value;
      });
    } else if (editAttr == EditAttr.mobile) {
      final ac = _normalizeAreaCode(areaCode.value);
      await LoadingView.singleton.wrap(
        asyncFunction: () => Apis.updateUserInfo(
          userID: OpenIM.iMManager.userID,
          phoneNumber: value,
          areaCode: ac,
        ),
      );
      imLogic.userInfo.update((val) {
        val?.phoneNumber = value;
        val?.areaCode = ac;
      });
    } else if (editAttr == EditAttr.email) {
      if (defaultValue?.isNotEmpty == true && value.isEmpty) {
        IMViews.showToast(StrRes.plsEnterEmail);
        return;
      }
      await LoadingView.singleton.wrap(
        asyncFunction: () => Apis.updateUserInfo(
          userID: OpenIM.iMManager.userID,
          email: value,
        ),
      );
      imLogic.userInfo.update((val) {
        val?.email = value;
      });
    } else if (editAttr == EditAttr.bio) {
      await LoadingView.singleton.wrap(
          asyncFunction: () => Apis.updateUserInfo(
            userID: OpenIM.iMManager.userID,
            ex: inputCtrl.text.trim(),
          ).then((value) => imLogic.userInfo.update((val) {
                val?.ex = inputCtrl.text.trim();
              })),
        );
    } else if (editAttr == EditAttr.area) {
      await  LoadingView.singleton.wrap(
          asyncFunction: () => Apis.updateUserInfo(
            userID: OpenIM.iMManager.userID,
            areaCode: inputCtrl.text.trim(),
          ).then((value) => imLogic.userInfo.update((val) {
                val?.areaCode = inputCtrl.text.trim();
              })),
        );
      imLogic.userInfo.update((val) {
        val?.areaCode = value;
      });
    }
    Get.back();
  }

  String? _normalizeAreaCode(String? input) {
    if (input == null || input.isEmpty) return null;
    final match = RegExp(r"\+?\d+").firstMatch(input);
    if (match == null) return input.startsWith('+') ? input : '+$input';
    final code = match.group(0)!;
    return code.startsWith('+') ? code : '+$code';
  }
}